url="$1"
quality="$2"

download_video(){
  echo "Downloading video...."
  j=0
  while [ "$native_file_size" != "$remote_file_size" ]; do
    j="`expr $j + 1`"
    if [ "$j" -gt 10 ]; then
      echo "Too many re-tries! Exiting...."
      exit 1
    fi
    curl -L -C - -o $tmpdir/$video_file --progress-bar $video_url
    native_file_size="`stat --printf=\"%s\" $tmpdir/$video_file 2> /dev/null`"
    if [ "$remote_file_size" == "" ]; then
      remote_file_size="`echo \"$response\" | tac | grep -i 'Content-Length' | awk '{print $2}'`"
    fi
  done
}

if [ \( "$url" == "-h" \) -o \( "$url" == "--help" \) ]; then
  echo "Usage: $0 URL [high|low]"
  exit 0
fi

if [ "$url" == "" ]; then
  echo "No URL provided! Exiting...."
  exit 1
fi

curl -I $url 2>/dev/null > url_check.txt
curl_status="$?"
http_status="`cat url_check.txt | head -n 1 | awk '{print $2}'`"
if [ "$curl_status" != 0 ]; then
  echo "cURL Error: $curl_status. Exiting...."
  rm url_check.txt
  exit 1
fi
if [ "$http_status" != 200 ]; then
  echo "URL Error: $http_status. Exiting...."
  rm url_check.txt
  exit 1
fi
rm url_check.txt

video_id="`echo $url | cut -d '/' -f 5`"
tmpdir="tmp_$video_id"
mkdir -p $tmpdir

if [ "$quality" == "low" ]; then
  scrape_string="video_alt_url"
else
  scrape_string="video_url"
fi

video_url=""
i=0
while [ "$video_url" == "" ]; do
  i="`expr $i + 1`"
  if [ "$i" -gt 10 ]; then
    echo "Too many re-tries! Exiting...."
    exit 1
  fi
  echo -n "Requesting video page.... "
  curl -L -o $tmpdir/page.html --silent $url
  if [ "`cat $tmpdir/page.html 2> /dev/null`" == "" ]; then
    echo "Invalid response! Exiting...."
    exit 1
  fi
  video_url="`cat $tmpdir/page.html | grep $scrape_string | cut -d '"' -f 2`"
  if [ "$video_url" == "" ]; then
    echo "Failed to scrape video URL!"
  fi
  echo "Done!"
done

video_file="`echo $video_url | tr '/' '\n' | grep '.mp4'`"
response="`curl --silent -I -L $video_url`"
remote_file_size="`echo \"$response\" | tac | grep 'content-length' | awk '{print $2}'`"
native_file_size="`stat --printf=\"%s\" $tmpdir/$video_file 2> /dev/null`"
if [ "$native_file_size" == "" ]; then
  native_file_size="0"
fi
if [ ! -f "$tmpdir/$video_file" ]; then
  download_video
else
  if [ "$native_file_size" == "$remote_file_size" ]; then
    echo "Already downloaded. Exiting...."
    exit 0
  else
    download_video
  fi
fi

echo "Download Complete!"

echo -e "Finalizing... "
mv $tmpdir/$video_file $video_file
echo "Done!"
echo -n "Cleaning up temporary files.... "
sleep 1
rm -rf $tmpdir
echo "Done!"
